 <!--
* description: 计划编辑
* author: wangml
* createdDate: 2020-12-5
-->
<template>
  <section class="cartypeQuery">
    <el-dialog
      id="cartypeq"
      v-dialogDrag
      v-loading="editloading"
      :title="title"
      :visible.sync="popupsVisible"
      :width="editWidth"
      center
      :append-to-body="true"
      :lock-scroll="true"
      :before-close="handleClose"
    >
      <dialogHeader
        slot="title"
        :title="title"
        :style-type="$store.state.app.dialogType"
      />
      <div style="padding:10px">
        <template v-for="comps in editForms">
          <div :key="comps.tid" class="filter-container filter-params">
            <h3 v-if="comps.title" :style="styleObj">{{ comps.title }}</h3>
            <el-row ref="vailComponentList1" :gutter="26">
              <component
                :is="comp.component"
                v-for="comp in comps.data.filter(o => o.isMust === true)"
                :ref="comp.isRequire ? comp.isRequire+ comp.compKey : comp.compKey"
                :key="comp.compKey"
                :validrule="comp.validrule"
                :code-field="comp.codeField"
                :text-field="comp.textField"
                :popups-key="comp.compKey"
                :code="formField[comp.codeField]"
                :parent-fileds="comp.parentFileds"
                :disabled="comp.disabled"
                :is-require="comp.isRequire"
                :is-mul="comp.isMul"
                :span="comp.span || 24"
                :label-name="comp.labelName"
                :format="comp.format"
                :lookuptype="comp.lookuptype"
                :data-to-object="comp.dataToObj"
                :date-options-type="comp.dateOptionsType"
                :date-type="comp.dateType"
                :custom-obj="comp.customObj"
                :options="comp.options"
                :o-fields="comp.oFields"
                @changeCode="getComponentCode"
                @focusCode="getFocusCode"
              />
            </el-row>
          </div>
        </template>
        <el-divider />
        <div slot="footer" class="dialog-footer" style="margin:10px">
          <el-button size="mini" type="primary" icon="iconfont  icon-confirm" @click="save">保存 </el-button>
          <el-button size="mini" type="info" @click="cancel">取消</el-button>
          <el-button size="mini" type="info" @click="clear">清除</el-button>
        </div>
      </div>
    </el-dialog>
  </section>
</template>
<script>

import Vue from 'vue'
import { formMixins } from '@/components/mixins/formMixins'
import api from '@/api/planReport'
export default {
  name: 'EditPage',
  components: {
    lableName: () => import('@/components/lableName'), // 标题溢出样式组件
    dialogHeader: () => import('@/components/dialogHeader') // 弹窗标题,
  },
  mixins: [formMixins],
  props: {
    title: { type: String, default: '' },
    popupsVisible: { type: Boolean, default: false },
    editForms: { type: Array, default: () => ([]) },
    editWidth: { type: String, default: '55%' },
    code: { type: String, default: '' },
    comType: { type: String, default: '' },
    codeField: { type: String, default: '' },
    popupsKey: { type: String, default: '' },
    isMul: { type: Boolean, default: true },
    validrule: {
      type: Object,
      default: () => {}
    }
  },
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      })
  },
  data() {
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      editloading: false,
      tableComponents: [],
      genCodeFiled: null,
      styleObj: { borderLeft: null },
      curPopupsVisible: this.popupsVisible,
      formField: {
        makingMonth: '',
        planMonth: '',
        planWeek: '',
        carSeriesId: '',
        carSeriesCn: '',
        carConfigId: '',
        carConfigCn: '',
        optionalPagId: '',
        optionalPagName: '',
        carColorId: '',
        carColorName: '',
        carIncolorId: '',
        carIncolorName: '',
        ttCode: '',
        planNum: ''
      }

    }
  },
  watch: {
    'formField': {
      handler(form) {
        const { carConfigCn, optionalPagName, carColorName, carIncolorName } = form
        if (carConfigCn || optionalPagName || carColorName || carIncolorName) {
          this.formField.ttCode = carConfigCn.slice(0, 13) + optionalPagName.slice(0, 5) + carColorName.slice(0, 3) + carIncolorName.slice(0, 1)
        }
        if (new Date(form.planMonth) <= new Date(form.makingMonth)) {
          this.formField.planMonth = ''
          const comp = this.$refs['trueplanMonthComp'][0]
          comp.modelCode = ''
          this.$alert('计划月份大于制定月份，请重新选择!', '提示', {
            confirmButtonText: '确定'
          }).then(() => {
            comp.$children[0].$children[1].focus()
          })
        }
      },
      deep: true
    },
    'popupsVisible': {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            const {
              planMonth,
              planWeek,
              carSerId,
              carSeriesCn,
              carSeriesCode,
              carConfigId,
              carConfigCode,
              carConfigCn,
              carOptionalpagId,
              optionalPagName,
              optionalPagCode,
              carColorId,
              carColorName,
              carColorCode,
              carIncolorId,
              carIncolorCode,
              carIncolorName,
              ttCode,
              urgent,
              planNum
            } = this.dynamicEditRowData
            Object.assign(this.formField, {
              planMonth,
              planWeek,
              carSeriesId: carSerId,
              carSeriesCn: carSeriesCode + carSeriesCn,
              carConfigId,
              carConfigCn: carConfigCode + carConfigCn,
              optionalPagId: carOptionalpagId,
              optionalPagName: optionalPagCode + optionalPagName,
              carColorId,
              carColorName: carColorCode + carColorName,
              carIncolorId,
              carIncolorName: carIncolorCode + carIncolorName,
              ttCode,
              urgent: urgent === '是' ? '1' : '0',
              planNum
            })
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.tableComponents = this.editForms.reduce((pre, cur) => [...pre, ...cur.data], [])
  },

  mounted() {
    this.setColor()
  },
  methods: {
    // 保存按钮点击事件
    save() {
      this.$utils.validataMoth(this, 'validpopup')
      // eslint-disable-next-line no-undef
      if (this.valid) {
        this.editloading = true
        const reqData = this.$utils.deepCopy(this.formField)
        reqData['carOptionalpagId'] = reqData['optionalPagId']
        reqData['carSerId'] = reqData['carSeriesId']
        reqData['updateControlId'] = this.dynamicEditRowData.updateControlId
        reqData['monthPlanId'] = this.dynamicEditRowData.monthPlanId
        reqData['salesPlanId'] = this.dynamicEditRowData.salesPlanId
        // reqData['carInColorId'] = reqData['carIncolorId']
        // delete reqData.carIncolorId
        this.$requestAPI({
          apiUrl: this.title === '销售计划跟踪'
            ? api.SalePlanTrackingEdit.APIUrl
            : api.update.APIUrl,
          variables: reqData
        }).then(response => {
          this.editloading = false
          this.$message(response.msg)
          if (response.result === '1') {
            this.$emit('close', '1')
          }
        }).catch(err => {
          this.editloading = false
          this.$message(err.response.data.msg)
        })
      }
    },
    // 取消按钮点击事件
    cancel() {
      this.$emit('close', '')
    },
    // 清除按钮点击事件
    clear() {
      this.formField.ttCode = ''
      this.formField.carSeriesId = '',
      this.formField.carSeriesCn = '',
      this.formField.carConfigId = '',
      this.formField.carConfigCn = '',
      this.formField.optionalPagId = '',
      this.formField.optionalPagName = '',
      this.formField.carColorId = '',
      this.formField.carColorName = '',
      this.formField.carIncolorId = '',
      this.formField.carIncolorName = '',
      this.formField.planNum = ''
      this.resetIconV()
    },
    // 避免 bug
    onCreated() {
      if (this.formField === null) {
        this.formField = { carBrandCode: '' }
      }
    },
    // 生成formField
    genUtil: (array) => (attr1 = 'codeField', attr2 = 'textField') => array.reduce((p, c) => {
      p[c[attr1]] = ''
      // eslint-disable-next-line no-prototype-builtins
      c.hasOwnProperty(attr2) ? p[c[attr2]] = '' : ''
      return p
    }, {}),
    // 设置h3标题颜色
    setColor() {
      const nowSystemColor = this.$store.getters.nowTheme.backgroundColor
      this.styleObj.borderLeft = `5px solid ${nowSystemColor}`
    },
    // 隐藏(重置)验证图标
    resetIconV() {
      this.$nextTick(() => {
        for (const comp in this.$refs) {
          if (comp.includes('true')) {
            this.$refs[comp][0].$children[0].$children[2].iconV = '3'
          }
        }
      })
    },
    // 关闭弹窗
    handleClose(type) {
      this.resetIconV()
      this.$emit('close', type)
    }

  }
}
</script>

<style lang="css" scoped>
  h3 {
    padding-left: 10px;
    text-align: left;
    font-weight: 600;
  }

  h3 button.el-button {
    float: right;
    margin-right: 10px;
  }
  >>> div.el-col.el-col-24 {
    margin-bottom: 10px;
  }

  .dialog-footer {
    float: right;
  }
  >>>.el-dialog__footer {
    overflow: hidden;
    padding: 10px 24px;
  }
</style>
